<template>
  <div class="main_goodsInfo">
    <el-dialog title="评价内容" v-model="evaluateDialogTableVisible">
      <el-table :data="evaluateData" height="400px">
        <el-table-column property="content" label="内容"></el-table-column>
        <el-table-column
          property="inputTime"
          label="评价时间"
          width="200"
        ></el-table-column>
        <el-table-column label="评价等级" width="200">
          <template #default="scope">
            <el-rate v-model="scope.row.grade" disabled></el-rate>
          </template>
        </el-table-column>
        <el-table-column
          property="feedbackContent"
          label="回复内容"
          width="200"
        ></el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog v-model="BuyDialogFormVisible" title="购买信息" width="500">
      <el-form :model="Buyform">
        <el-table :data="Buyform.list" bordered height="400">
          <el-table-column label="菜品名称" prop="menuName"></el-table-column>
          <el-table-column label="图片">
            <template #default="scope">
              <el-image
                style="width: 50px; height: 50px; border-radius: 5px"
                :src="scope.row.menuPicture"
                fit="cover"
                ><template #error>
                  <div class="image-slot">
                    <el-icon><icon-picture /></el-icon>
                  </div> </template
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column
            label="菜品价格"
            prop="menuPrice"
            width="100"
          ></el-table-column>
          <el-table-column label="菜品数量" width="150">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.count"
                :min="1"
                :max="100"
                size="small"
                @change="handleChange"
              />
            </template>
          </el-table-column>
        </el-table>

        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
            v-model="Buyform.demo"
            style="width: 240px"
            :rows="2"
            type="textarea"
            placeholder="请填写你的备注信息"
          />
        </el-form-item>
        <el-form-item label="点餐类型" :label-width="formLabelWidth">
          <el-select-v2
            v-model="Buyform.type"
            :options="OrderOption"
            placeholder="请选择点餐类型"
            size="large"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item
          label="地址"
          :label-width="formLabelWidth"
          v-show="Buyform.type == 2"
        >
          <el-select-v2
            v-model="Buyform.addressId"
            :options="AddressOption"
            placeholder="请选择地址"
            size="large"
            style="width: 440px"
          />
        </el-form-item>

        <el-tag type="warning" effect="dark">外卖需多支付2元配送费</el-tag>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="BuyDialogFormVisible = false">取消</el-button>

          <el-button type="primary" @click="createOrder"> 确认购买 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-breadcrumb separator="/" style="margin-top: 20px; margin-bottom: 20px">
      <el-breadcrumb-item :to="{ path: '/manager/order/tackOut' }"
        >首页</el-breadcrumb-item
      >
      <el-breadcrumb-item :to="{ path: '/manager/order/shopInfo' }"
        >商家信息</el-breadcrumb-item
      >
    </el-breadcrumb>
    <div style="display: flex; justify-content: end">
      <el-button @click="viewEvaluate">查看评价</el-button>

      <el-button type="warning" v-show="!collectFlag" @click="collectShop"
        >收藏</el-button
      >
      <el-button type="info" v-show="collectFlag" @click="cancelCollectShop"
        >取消收藏</el-button
      >
    </div>
    <div style="display: flex; justify-content: space-between; align-items: center">
      <div style="display: flex; align-items: center; font-size: 22px">
        <el-image
          style="width: 50px; height: 50px; border-radius: 5px"
          :src="shopInfo.shopImg"
          fit="cover"
        ></el-image>
        <div>
          {{ shopInfo.shopName }}
        </div>
      </div>
      <div>
        <el-input
          v-model="menuNameSearch"
          style="width: 240px"
          placeholder="请输入菜品名称"
        />
        <el-button @click="getMenuInfo">搜索</el-button>
      </div>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      height="60vh"
      ref="multipleTableRef"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="menuName" label="菜品名称" />
      <el-table-column label="菜品图片" width="150">
        <template #default="scope">
          <el-image
            style="width: 50px; height: 50px; border-radius: 5px"
            :src="scope.row.menuPicture"
            fit="cover"
            ><template #error>
              <div class="image-slot">
                <el-icon><icon-picture /></el-icon>
              </div> </template
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="价格" prop="menuPrice" width="150"></el-table-column>
      <el-table-column label="备注" prop="menuDescribe"></el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageSize"
      v-model:page-size="pageItem"
      :page-sizes="[20, 40, 50, 100]"
      background="blue"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageTotal"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <div style="display: flex; justify-content: end">
      <el-button type="primary" @click="BuyThing">购买</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Picture as IconPicture } from "@element-plus/icons-vue";
import router from "@/router";
import axios from "axios";
import { ref, onMounted, reactive } from "vue";
const menuNameSearch = ref("");
const evaluateData = ref([]);
import { ElMessage, ElTable } from "element-plus";
const evaluateDialogTableVisible = ref(false);
const shopId = router.currentRoute.value.query.id;
const collectFlag = ref(false);
const token = localStorage.getItem("student_auth_token");
const AddressOption = ref([]);
const shopInfo = ref({
  shopImg: "",
  shopState: 0,
  shopId: "",
  shopName: "",
});
const Buyform = ref({
  list: [], //菜单列表
  demo: "",
  addressId: "",
  type: 1,
});
const OrderOption = [
  {
    label: "堂食",
    value: 1,
  },
  {
    label: "外卖",
    value: 2,
  },
];
const formLabelWidth = "100px";
const BuyDialogFormVisible = ref(false);
const tableData = ref([]);
const pageSize = ref(1); //页数
const pageTotal = ref(0);
const pageItem = ref(20); //每页的个数
const BuyThing = () => {
  if (Buyform.value.list.length == 0) {
    ElMessage({
      type: "warning",
      message: "购物车至少需要选择一个菜品",
    });
    return;
  }
  BuyDialogFormVisible.value = true;
};
const handleChange = (value: number) => {
  // console.log(value);
};
const viewEvaluate = () => {
  axios
    .get("/api/evaluate/select/shopId/" + shopId, {
      headers: {
        token: token,
      },
    })
    .then((res) => {
      evaluateData.value = res.data.message;
      evaluateDialogTableVisible.value = true;
      // console.log(res);
    })
    .catch((err) => {
      console.log(err);
    });
};
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  // console.log("code line-131 \n\r😏 val:\n\r", val);
  Buyform.value.list = val;
  Buyform.value.list.forEach((el) => {
    el.count = 1;
  });
};
const getUserAddress = () => {
  axios
    .get("/api/userAddress/select/option", {
      headers: {
        token: token,
      },
    })
    .then((res) => {
      // console.log("code line-264 \n\r😁 res:\n\r", res);

      if (res.data.success) {
        AddressOption.value = res.data.message;
        Buyform.value.addressId = AddressOption.value[0].value;
      }
    })
    .catch((err) => {});
};

const getCollectStation = () => {
  axios
    .get("/api/collect/choose/" + shopId, {
      headers: {
        token: token,
      },
    })
    .then((res) => {
      // console.log("code line-209 \n\r😀 res:\n\r", res);
      collectFlag.value = res.data.success;
    })
    .catch((err) => {});
};
getCollectStation();
getUserAddress();
const collectShop = () => {
  axios
    .get("/api/collect/follow/" + shopId, {
      headers: {
        token: token,
      },
    })
    .then((res) => {
      // console.log("code line-192 \n\r😀 res:\n\r", res);
      if (res.data.success) {
        ElMessage({
          type: "success",
          message: "收藏成功",
        });
        getCollectStation();
      }
    })
    .catch((err) => {});
};

const cancelCollectShop = () => {
  axios
    .get("/api/collect/cancel/follow/" + shopId, {
      headers: {
        token: token,
      },
    })
    .then((res) => {
      // console.log("code line-192 \n\r😀 res:\n\r", res);
      if (res.data.success) {
        ElMessage({
          type: "success",
          message: "取消收藏成功",
        });
      }
      getCollectStation();
    })
    .catch((err) => {});
};

const getShopInfo = () => {
  axios
    .get("/api/shop/get/" + router.currentRoute.value.query.id, {
      headers: {
        token: token,
      },
    })
    .then((res) => {
      // console.log("res :>> ", res);
      shopInfo.value = res.data.message;
    })
    .catch((err) => {
      console.log(err);
    });
};
const getMenuInfo = () => {
  axios
    .get(
      "/api/menu/select/" +
        shopId +
        "/" +
        pageSize.value +
        "/" +
        pageItem.value +
        "?menuName=" +
        menuNameSearch.value,
      {
        headers: {
          token: token,
        },
      }
    )
    .then((res) => {
      // console.log("code line-134 \n\r😇 res:\n\r", res);

      const msg = res.data.message;
      pageTotal.value = msg.total;
      tableData.value = msg.list;
    })
    .catch((err) => {});
};

const handleSizeChange = (val: number) => {
  // console.log(`${val} items per page`);
  pageItem.value = val;
  getMenuInfo();
};
const handleCurrentChange = (val: number) => {
  // console.log(`current page: ${val}`);
  pageSize.value = val;
  getMenuInfo();
};

const createOrder = () => {
  const orderMenuList = [];
  Buyform.value.list.forEach((el) => {
    orderMenuList.push({
      count: el.count,
      menuId: el.menuId,
    });
  });
  if (Buyform.value.type == 2) {
    if (Buyform.value.addressId == "") {
      ElMessage({
        type: "error",
        message: "由于你点餐类型为外卖，地址信息必须选择",
      });
      return;
    }
  }
  if (Buyform.value.type == 1) {
    Buyform.value.addressId = "";
  }

  // console.log(orderMneuList);//菜单列表以及个数
  const req = {
    orderInfo: {
      addressId: Buyform.value.addressId,
      demo: Buyform.value.demo,
      type: Buyform.value.type,
      shopId: shopId,
    },
    menuInfos: orderMenuList,
  };

  /**
   * 购买
   */
  axios
    .post("/api/order/create", req, {
      headers: {
        token: token,
      },
    })
    .then((res) => {
      // console.log("code line-407 \n\r😑 res:\n\r", res);
      if (res.data.success) {
        ElMessage({
          type: "success",
          message: "订单创建成功",
        });
        router.push("/manager/order/viewInformation?id=" + res.data.message.orderId);
      } else {
        ElMessage({
          type: "error",
          message: "订单创建失败",
        });
      }
    })
    .catch((err) => {});
};

onMounted(() => {
  // 在这里可以执行与mounted生命周期钩子相关的任何操作
  getShopInfo(); //获取商店信息
  getMenuInfo(); //获取菜单信息
});
</script>

<style lang="scss" scoped>
.main_goodsInfo {
  height: 100%;
  width: 100%;
}
</style>
